package Hot100.Tree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class invertTree {
    List<Integer> list = new ArrayList<>();
    TreeNode root;

    public static void main(String[] args) {
        int[] root = {4,2,7,1,3,6,9};
        invertTree invertTree = new invertTree();
        invertTree.insert(root);


        TreeNode node = invertTree.invertTree(invertTree.root);
        System.out.println(invertTree.invertTree(invertTree.root).val);
    }

    public TreeNode invertTree(TreeNode root) {
        if(root == null)
            return null;

        invertTree invertTree = new invertTree();
        inorder(root);


        int[] values;
        values = list.stream().mapToInt(Integer::intValue).toArray();
        invertTree.insert(values);
        return invertTree.root;
    }
    public void inorder(TreeNode root){

        if(root == null)
            return;
        Queue<TreeNode> queue = new LinkedList<>();
        int i = 0;
        list.add(root.val);
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode current = queue.poll();

            if(current.right != null){
                list.add(current.right.val);
                queue.offer(current.right);
            }
            if(current.left != null){
                list.add(current.left.val);
                queue.offer(current.left);
            }
        }
    }

    public void insert(int[] values) {
        if (values == null || values.length == 0) {
            return;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        int i = 0;

        root = new TreeNode(values[i++]);
        queue.offer(root);

        while (!queue.isEmpty()) {
            TreeNode current = queue.poll();

            if (i < values.length) {
                int leftVal = values[i++];
                if (leftVal != -1) {
                    current.left = new TreeNode(leftVal);
                    queue.offer(current.left);
                }
            }

            if (i < values.length) {
                int rightVal = values[i++];
                if (rightVal != -1) {
                    current.right = new TreeNode(rightVal);
                    queue.offer(current.right);
                }
            }
        }
}}
